package com.jfinal.ext.util.file;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 江理_网猿 (timor)
 * @date 2020/10/7 0007
*/
public enum FileHash {
    /**
     * md5
     */
    MD5("md5"),
    SHA1("sha1"),
    SHA256("sha256"),
    SHA512("sha512")
    ;

    private final MessageDigest messageDigest;


    FileHash(@NotNull String algorithm) {
        try {
            this.messageDigest = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(algorithm, e);
        }
    }

    public String hash(File file) throws IOException {
        try (final FileInputStream inputStream = new FileInputStream(file)) {
            final int maxLength = 1024;
            byte[] buffer = new byte[maxLength];
            int length;
            while ((length = inputStream.read(buffer, 0, maxLength)) > 0) {
                messageDigest.update(buffer, 0, length);
            }
            return new BigInteger(1, messageDigest.digest()).toString(16);
        }
    }

    public String getAlgorithm() {
        return messageDigest.getAlgorithm();
    }

}